#ifndef __UDP_CLIENT_HPP__
#define __UDP_CLIENT_HPP__

#include <iostream>
#include <string>
#include <memory>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"
#include "Thread.hpp"

#define SIZE 1024

class UDPClient
{
private:
    uint16_t getPort()
    {
        return _serPort;
    }

    const char* getIp()
    {
        return _serIp.c_str();
    }

    int getSock()
    {
        return _sock;
    }

public:
    UDPClient(std::string ip, uint16_t port)
        : _sock(-1)
        , _serIp(ip)
        , _serPort(port)
        ,_recv(nullptr)
        ,_send(nullptr)
    {
        _sock = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sock < 0)
        {
            perror("socket");
            exit(1);
        }

        _recv=new Thread(1,udpRecv,this);
        _send=new Thread(2,udpSend,this);
    }

    void start()
    {
        _send->create();
        _recv->create();
    }

    static void* udpRecv(void* args)
    {
        ThreadData* td=(ThreadData*)args;
        UDPClient* uc=(UDPClient*)td->_args;

        struct sockaddr_in tmp;
        memset(&tmp,0,sizeof(tmp));
        socklen_t len=sizeof(tmp);

        char buff[SIZE];
        while(true)
        {
            ssize_t s=recvfrom(uc->getSock(),buff,sizeof(buff)-1,0,(struct sockaddr*)&tmp,&len);
            if(s>0)
            {
                buff[s]='\0';
                printf("%s\n",buff);

                //为了实现输入和输出不同会话，在上层会进行重定向，将标准输出重定向到命名管道中，刷新策略改变，所以需要强制刷新
                fflush(stdout);
            }
        }
    }
    static void* udpSend(void* args)
    {
        ThreadData* td=(ThreadData*)args;
        UDPClient* uc=(UDPClient*)td->_args;

        //填充服务器字段
        struct sockaddr_in server;
        memset(&server,0,sizeof(server));
        server.sin_family=AF_INET;
        server.sin_port=htons(uc->getPort());
        server.sin_addr.s_addr=inet_addr(uc->getIp());

        std::string message;
        while(true)
        {
            std::cerr<<"请输入信息: ";
            std::getline(std::cin,message);
            if(message=="quit")
            {
                exit(0);
            }
            sendto(uc->getSock(),message.c_str(),message.size(),0,(struct sockaddr*)&server,sizeof(server));
        }
    }

    ~UDPClient()
    {
        _recv->join();
        _send->join();
        close(_sock);
        delete _recv;
        delete _send;
    }

private:
    int _sock;          // 套接字
    std::string _serIp; // 服务端IP
    uint16_t _serPort;  // 服务端Port
    Thread* _recv;//收数据线程
    Thread* _send;//发数据线程
};

#endif